package cn.xianshu.user.controller;

import cn.xianshu.basic.exception.BasicException;
import cn.xianshu.basic.util.AxiosResult;
import cn.xianshu.basic.util.PageList;
import cn.xianshu.user.domain.User;
import cn.xianshu.user.dto.UserDto;
import cn.xianshu.user.query.UserQuery;
import cn.xianshu.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;

    @GetMapping("/{id}")
    public User findOne(@PathVariable("id") Long id){
        return userService.findById(id);
    }

    @GetMapping
    public List<User> findAll(){
        return userService.findAll();
    }

    @DeleteMapping("/{id}")
    public AxiosResult delete(@PathVariable("id") Long id){
        try {
            userService.delete(id);
            return AxiosResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AxiosResult.me().setMessage("删除失败，请稍后重试！");
        }
    }

    @PutMapping
    public AxiosResult addAndUpdate(@RequestBody User user){
        try {
            if (user.getId() == null){
                userService.insert(user);
            } else {
                userService.update(user);
            }
            return AxiosResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AxiosResult.me().setMessage("系统繁忙，请稍后重试！");
        }
    }

    @PostMapping
    public PageList<User> queryPage(@RequestBody UserQuery query){
        return userService.pageQuery(query);
    }

    /**
     * * 可以使用对象接收，也可以用map
     * domain, entiry, pojo....   // 跟数据库表对应的
     * dto, vo ,query ....    //  封装参数用的
     * @return
     * @param userDto
     */
    @PostMapping("/phone/register")
    public AxiosResult phoneRegister(@RequestBody UserDto userDto){
        try {
            userService.phoneRegister(userDto);
            return AxiosResult.me();
        } catch (BasicException e) {
            e.printStackTrace();
            return AxiosResult.me().setMessage(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AxiosResult.me().setMessage("系统繁忙!");
        }
    }

}
